﻿using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using Shop.DB;
using Shop.Domain.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Shop.Application.Cart
{
    public class GetOrder
    {
        private ISession _session;
        private DBContext _context;

        public GetOrder(ISession session, DBContext context)
        {
            _session = session;
            _context = context;
        }

        public Response Do()
        {
            //获取session
            var str = _session.GetString("Cart");
            var carts = JsonConvert.DeserializeObject<List<CartProduct>>(str);

            var ProductList = _context.Stocks
                .AsEnumerable()
                .Where(x => carts.Any(y => y.StockID == x.StockID))
                .Select(x => new Product
                {
                    ProductID = x.ProductID,
                    StockID = x.StockID,
                    Name = _context.Products.FirstOrDefault(y => y.ProductID == x.ProductID).Name,
                    Value = _context.Products.FirstOrDefault(y => y.ProductID == x.ProductID).Value,
                    Count = carts.FirstOrDefault(y => y.StockID == x.StockID).Count
                }).ToList();

            var customerInfo = JsonConvert.DeserializeObject<CustomerInformation>(_session.GetString("CustomerInfo"));
            return new Response
            {
                Products = ProductList,
                CustomerInfo = new CustomerInformation
                {
                    UserName = customerInfo.UserName,
                    Email = customerInfo.Email,
                    Address = customerInfo.Address,
                    PhoneNumber = customerInfo.PhoneNumber,
                    City = customerInfo.City,
                    PostCode = customerInfo.PostCode
                }
            };
        }

        public class Response
        {
            public IEnumerable<Product> Products { get; set; }
            public CustomerInformation CustomerInfo { get; set; }
            public decimal GetTotalCharge() => Products.Sum(x => x.Value * x.Count);
        }

        public class Product
        {
            public Guid ProductID { get; set; }
            public Guid StockID { get; set; }
            public string Name { get; set; }
            public decimal Value { get; set; }
            public int Count { get; set; }
        }
    }
}
